package sfbot;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class GeneralConsensus implements CommandModel{
	private boolean isActivated;
	private final String[] cmds = {"opinion", "--", "++"};
	private Map<User, List<String>> opinions;
	int positive = 0;
	int negative = 0;
	
	public GeneralConsensus(){
		this(new HashMap<User, List<String>>(), 0, 0);
	}
	
	public GeneralConsensus(Map<User, List<String>> opinions, int startPos, int startNeg){
		if(opinions == null)
			throw new NullPointerException("User/Message map cannot be null");
		this.opinions = opinions;
		positive = startPos;
		negative = startNeg;
	}
	
	@Override
	public void activate() {
		isActivated = true;
	}

	@Override
	public void deactivate() {
		isActivated = false;
	}

	@Override
	public List<String> getCommands() {
		ArrayList<String> commands = new ArrayList<String>();
		for(String s : cmds)
			commands.add(s);
		return commands;
	}

	@Override
	public void recieveMessage(String msg, User user, Channel channel) {
		String cmd;
		if(msg.indexOf(" ") > 0)
			cmd = msg.substring(0, msg.indexOf(" "));
		else
			cmd = msg;
		if(cmd.equalsIgnoreCase(cmds[0])) {
			recordOpinion(msg.substring(msg.indexOf(" ", 0), msg.length()), user, channel);
		} else if (cmd.equalsIgnoreCase(cmds[1])){
			negative--;
			sendMessage(String.format("Salesforce has a score of: %-4d (+%d/%d)", positive+negative, positive, negative), channel.getName());
		} else if (cmd.equalsIgnoreCase(cmds[2])){
			positive++;
			sendMessage(String.format("Salesforce has a score of: %-4d (+%d/%d)", positive+negative, positive, negative), channel.getName());
		}
	}

	private void recordOpinion(String msg, User user, Channel channel) {
		if(!status() && msg.isEmpty())
			return;
		
		msg = steralizer(msg);
		
		List<String> userOpinions;
		if((userOpinions = opinions.get(user)) == null){
			userOpinions = new LinkedList<String>();
			opinions.put(user, userOpinions);
		}
		userOpinions.add(msg);
		sendMessage("@" + user.getNick() + ": Opinion Recorded.", channel.getName());
	}
	
	private void sendMessage(String msg, String des){
		System.out.println(msg);
	}
	
	private String steralizer(String msg){
		msg = msg.trim();
		if(msg.startsWith("/"))
			return msg.substring(1, msg.length());
		else
			return msg;
	}

	@Override
	public boolean status() {
		return isActivated;
	}

}
